package com.example.gomi.intelligentcitypipe;

import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.gomi.intelligentcitypipe.DAO.PipeInfo;
import com.example.gomi.intelligentcitypipe.serial.PipeProtocol;
import com.example.gomi.intelligentcitypipe.serial.SerialController;


public class TimerReaderThread extends Thread {

    private PipeProtocol pipeProtocol;
    private String version = null;
    public TimerReaderThread(PipeProtocol pipeProtocol,String version) {
        this.pipeProtocol = pipeProtocol;
        this.version = version;
    }

    @Override
    public void run() {
        super.run();
        while (SerialController.getInstance().getmRunFlag()&&SerialController.getInstance().getVersion().equals(this.version)) {
            //暂停的时候就等一下
            Log.e("填充字節線程,","開始運行,");
            while (SerialController.getInstance().getPause()) {
                Log.e("线程暂停,","线程暂停,");
                try {
                    Thread.sleep(900);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            //10次发送之后就开始重置
            if (this.pipeProtocol.increaseSendPackageCount() == 10) {

                if (this.pipeProtocol.getReceivePackageCount() == 0) {
                    Log.d("PipeProtocol", "Serial no data");
                    //只会有一个toast提示，未收到消息
                    Handler handler = SerialController.getInstance().getMessageReceiveHandler();
                    Message mssage = handler.obtainMessage();
                    mssage.what = PipeProtocol.SERIAL_NO_DATA;
                    mssage.obj = new PipeInfo();
                    mssage.sendToTarget();
                }
                this.pipeProtocol.resetReceiveAndSendPackageCounter();
            }
            //再次给硬件推送数据
            this.pipeProtocol.sendPackage();
            try {
                Thread.sleep(900);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
